import os
from extract_dxf_table import extract_table_blocks_to_excel,clean_excel_file
import os
import pandas as pd
from pathlib import Path
from utils import start_fentu,tiankui_parsing


def collect_files_with_keywords(root_dir: str, keywords=['远端机房设备平面布置图', '近端机房设备平面布置图']) -> list[str]:
    """
    收集 root_dir（递归）下文件名包含任一关键词的文件路径。
    :param root_dir: 要扫描的文件夹路径
    :param keywords: 关键词元组，默认 ('远端', '近端')
    :return: 符合条件的文件完整路径列表
    """
    matched_paths = []
    for dirpath, _, filenames in os.walk(root_dir):
        for file in filenames:
            # 去掉扩展名后再判断
            stem, _ = os.path.splitext(file)
            print("Stem:", stem)  # 打印 stem 的值
            print("Keywords:", keywords)  # 打印 keywords 的值
            for k in keywords:
                print(k)
            if any(k in stem for k in keywords):
                matched_paths.append(os.path.join(dirpath, file))

    print(matched_paths)
    return matched_paths


# if __name__ == "__main__":
def NumberOfDeviceQuestions(input_dxf_path,out_dxf_path):


    Path(out_dxf_path).mkdir(exist_ok=True)
    #分图处理
    dxf_sub_graph_files = start_fentu(out_dxf_path, input_dxf_path)
    # folder = "E:\python\MCP_s\cadsecond-processing\output"   # 支持从资源管理器拖拽路径
    result = collect_files_with_keywords(out_dxf_path)
    print("共找到符合条件的文件：", len(result))
    # for path in result:
    #     print(path)
    re = {}
    for dxf_file in result:
        re_key = ""
        if "近端" in dxf_file:
            re_key = "近端设备信息"
        elif "远端" in dxf_file:
            re_key = "远端设备信息"
        output_dir = os.path.dirname(dxf_file)
        parent_dir = os.path.dirname(output_dir)
        # 构造 retrieve_folder 路径
        retrieve_folder = os.path.join(parent_dir, "retrieve_folder")
        os.makedirs(retrieve_folder, exist_ok=True)  # 自动创建目录（如果不存在）
        # 构造 Excel 文件保存路径
        base_name = os.path.splitext(os.path.basename(dxf_file))[0]
        output_excel = os.path.join(retrieve_folder, base_name + "_tables.xlsx")
        # 执行提取和清洗
        extract_table_blocks_to_excel(dxf_file, output_excel)

        file_path = output_excel  # 即刚刚保存的路径
        #如果file_path没有则跳过
        if not os.path.exists(file_path):
            continue
        else:
            clean_excel_file(file_path)
            # 1. 读入文件
            df = pd.read_excel(file_path, sheet_name=0)  # 如有多个工作表请自行调整

            # 2. 保留“原有数量”或“设计数量”中至少有一个为数字的行
            mask = (
                    pd.to_numeric(df['原有数量'], errors='coerce').notna() |
                    pd.to_numeric(df['设计数量'], errors='coerce').notna()
            )
            df = df[mask]
            # 3. 合并两列为“数量”
            df['数量'] = (pd.to_numeric(df['原有数量'], errors='coerce').fillna(0) +
                          pd.to_numeric(df['设计数量'], errors='coerce').fillna(0))
            # 4. 删除名称列中等于“标签”或“标签辅料”的行
            df = df[~df['名称'].isin(['标签', '标签辅料'])]
            # 4. 保留需要的列并输出
            out = df[['名称', '数量']]
            out.to_excel(file_path, index=False)
            re[re_key]=dict(zip(df['名称'], df['数量']))

    tiankui_devisces = tiankui_parsing(collect_files_with_keywords(out_dxf_path, ["远端基站天馈安装示意图"])[0])
    if tiankui_devisces != []:
        re["天馈设备信息"] = tiankui_devisces
    else:
        re["天馈设备信息"] = tiankui_parsing(collect_files_with_keywords(out_dxf_path, ["远端基站天馈安装示意图"])[1])
    return re
def  PowerCalculation(input_dxf_path,out_dxf_path,dev_name):
    Path(out_dxf_path).mkdir(exist_ok=True)
    # 分图处理
    dxf_sub_graph_files = start_fentu(out_dxf_path, input_dxf_path)
    # folder = "E:\python\MCP_s\cadsecond-processing\output"   # 支持从资源管理器拖拽路径
    keyword = ["近端机房设备平面布置图"]
    if dev_name == "BBU机框":
        keyword = ["近端机房设备平面布置图"]
        power = 2100
    else:
        keyword = ["远端基站天馈安装示意图"]
        power = 1400
    result = collect_files_with_keywords(out_dxf_path,keyword)
    print("共找到符合条件的文件：", len(result))
    for dxf_file in result:
        output_dir = os.path.dirname(dxf_file)
        parent_dir = os.path.dirname(output_dir)
        # 构造 retrieve_folder 路径
        retrieve_folder = os.path.join(parent_dir, "retrieve_folder")
        os.makedirs(retrieve_folder, exist_ok=True)  # 自动创建目录（如果不存在）
        # 构造 Excel 文件保存路径
        base_name = os.path.splitext(os.path.basename(dxf_file))[0]
        output_excel = os.path.join(retrieve_folder, base_name + "_tables.xlsx")
        # 执行提取和清洗
        extract_table_blocks_to_excel(dxf_file, output_excel,required_keywords=['设备型号', '设备厂家'])

        file_path = output_excel  # 即刚刚保存的路径
        # 如果file_path没有则跳过
        if not os.path.exists(file_path):
            continue
        else:
            clean_excel_file(file_path)
            # 1. 读入文件
            df = pd.read_excel(file_path, sheet_name=0)  # 如有多个工作表请自行调整

            # 2. 保留“原有数量”或“设计数量”中至少有一个为数字的行
            mask = (
                    pd.to_numeric(df['原有数量'], errors='coerce').notna() |
                    pd.to_numeric(df['设计数量'], errors='coerce').notna()
            )
            df = df[mask]
            # 3. 合并两列为“数量”
            df['数量'] = (pd.to_numeric(df['原有数量'], errors='coerce').fillna(0) +
                          pd.to_numeric(df['设计数量'], errors='coerce').fillna(0))
            # 4. 删除名称列中等于“标签”或“标签辅料”的行
            df = df[~df['名称'].isin(['标签', '标签辅料'])]
            # 5. 读取名称中是“BBU”的设备  并查看列名中对应的“数量”
            df_bbu = df[df['名称'].str.contains(dev_name, na=False)]
            bbu_quantities = df_bbu['数量'].sum()
            print(dev_name,"数量:",bbu_quantities)
            return "{}的总功耗：{}W".format(dev_name,int(bbu_quantities*power))

# print(NumberOfDeviceQuestions("drawingLibrary/嘉兴海宁全1.dxf", "output"))
# print(PowerCalculation("drawingLibrary/嘉兴海宁全1.dxf", "output","RRU"))
# collect_files_with_keywords(root_dir="E:\python\MCP_s\cadsecond-processing\output",keywords=['天馈'])

import re

def extract_device_type(text: str) -> str | None:
    """
    从问句中提取设备类型：'BBU机框' 或 'AAU'
    规则：紧跟在“图纸上”之后、“设备”之前。
    """
    m = re.search(r'图纸上(.*?)设备', text)
    return m.group(1) if m else None

# 测试
if __name__ == '__main__':
    samples = "当前图纸上BBU机框设备的总功耗是多少？",
    # samples = "当前图纸上AAU设备的总功耗是多少？"

    m = re.search(r'图纸上(.*?)设备', samples)
    print(f"{samples}  -->  {extract_device_type(samples)}")
